package ca.intelliware.commons.virtualization.vmware;

import java.io.IOException;

import com.vmware.vim25.ManagedEntityStatus;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VirtualMachineSnapshotTree;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.VirtualMachineSnapshot;

public class Vm implements ca.intelliware.commons.virtualization.VMachine {
	private VirtualMachine virtualMachine;
	private String name;
	Vm(VirtualMachine virtualMachine) {
		this.virtualMachine = virtualMachine;
	}
	
	public String getStatus() {
		ManagedEntityStatus status = this.virtualMachine.getOverallStatus();
		return status.name();
	}

	public String getId() {
		if (name == null) {
			name = this.virtualMachine.getName();
		}
		return name;
	}


	public void revertToLastSnapshot() throws IOException {
		VirtualMachineSnapshotTree snapshotTree = this.virtualMachine
				.getSnapshot().getRootSnapshotList()[0];
		ManagedObjectReference managedObjectReference = findLastSnapshotInTree(snapshotTree);
		VirtualMachineSnapshot virtualMachineSnapshot = new VirtualMachineSnapshot(
				this.virtualMachine.getServerConnection(),
				managedObjectReference);
		virtualMachineSnapshot.revertToSnapshot_Task(null);
	}

	/**
	 * This assumes that there is only one tree and it takes the first child.
	 * 
	 * @param snapshotTree
	 * @return
	 */
	private ManagedObjectReference findLastSnapshotInTree(
			VirtualMachineSnapshotTree snapshotTree) {
		if (snapshotTree.getChildSnapshotList() != null
				&& snapshotTree.getChildSnapshotList().length > 0) {
			return findLastSnapshotInTree(snapshotTree.getChildSnapshotList()[0]);
		} else { // length == 0
			return snapshotTree.getSnapshot();
		}
	}

}
